package pers.burgess.xml.handler;

import org.dom4j.Document;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 
 * Xml Builder
 * 
 * @author Burgess
 *
 */
public class XmlBuilder {

	/**
	 * Build Xml content from list
	 * 
	 * @param list data list
	 * @return Xml content
	 * @throws IOException
	 */
    public static String buildXml(List list) throws IOException {
        if (list.size() > 0) {
            Class cls = list.get(0).getClass();
            Document document = new DOMDocument();
            document.setRootElement(new DOMElement(cls.getName().substring(cls.getName().lastIndexOf(".") + 1) + "s"));
            for (Object o: list) {
                DOMElement element = new DOMElement(cls.getName().substring(cls.getName().lastIndexOf(".") + 1));
                Field[] fields = o.getClass().getDeclaredFields();
                for (Field field: fields) {
                    try {
                        Method method = o.getClass().getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
                        DOMElement subElement = new DOMElement(field.getName());
                        subElement.setText(method.invoke(o).toString());
                        element.add(subElement);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
                document.getRootElement().add(element);
            }
            StringWriter stringWriter = new StringWriter();
            XMLWriter xmlWriter = new XMLWriter(stringWriter);
            xmlWriter.write(document);
            return stringWriter.toString();
        }
        return null;
    }

}
